# coding: utf8
'''it 基础工具类'''
from django.shortcuts import render
from it.models import Menus
# 集合库
import collections

def _get_menu_tree():
	'''获得菜单树字典'''
	menus = Menus.objects.order_by('order').values()
	# 按照声明的顺序添加, 避免顺序按key自动排序
	dict_menus = collections.OrderedDict()
	tree = collections.OrderedDict()
	# 遍历菜单转为字典
	for menu in menus:
		dict_menus[menu.get('id')] = menu

	# 遍历菜单, 将子菜单挂载到父菜单字典下
	for menu in menus:
		if menu.get('pid') > 0:	# 存在父菜单
			# 获取子菜单, 没有的赋予空字典
			children = dict_menus.get(menu.get('pid')).get('children', {})
			# 加入新的子菜单
			children.update({menu.get('id'): menu})
			# 重新挂载子菜单
			dict_menus.get(menu.get('pid'))['children'] = children

	# 遍历挂载完整的菜单, 将重复的子菜单过滤掉
	for id,menu in dict_menus.items():
		if not menu.get('pid') > 0:
			tree[id] = menu

	return tree


def _get_menu_html(tree, is_top):
	'''拼接菜单html代码, 使用回调方法'''
	# 第一级需要加样式
	if is_top:
		html = '<ul class="nav navbar-nav" data-in="fadeInDown" data-out="fadeOutUp">'
	else:
		html = '<ul class="dropdown-menu animated fadeOutUp">'

	# 循环当前级别的菜单
	for id,menu in tree.items():
		html += '<li class="dropdown">' if menu.get('children') else '<li>'
		html_a = '''<a href="%s" target="%s" 
				class="dropdown-toggle" data-toggle="dropdown">%s</a>'''
		html += (html_a if menu.get('children') else \
				'<a href="%s" target="%s">%s</a>') % \
				(menu.get('url'),menu.get('target'),menu.get('name'))

		# 判断是否有子菜单
		if menu.get('children', None):
			html += _get_menu_html(menu.get('children'), 0)

		html += '</li>'
	html += '</ul>'

	# 返回
	return html

def show_menu():
	'''为自定义模版标签提供html'''
	return _get_menu_html(_get_menu_tree(), 1)

def not_template(request):
	'''模版不存在'''
	return error(request, '程序出错了', '视图不存在')

def display(request, template, data={}):
	'''将数据显示到页面'''

	if template == '':
		return not_template(request)

	return render(request, template, data)

def post(request, template, data={}):
	'''响应POST提交'''

	if request.method != 'POST':
		return error(request)

	return display(request, template, data)



def message(req, title='提交成功!', links={}, default=0):
	'''通用消息处理视图,提供主视图调用'''
	callback = None
	links = links.items()
	if len(links) > default:
		callback = links[default]	# 默认第一个链接自动返回

	data = {
		'title': title,
		'links': links,
		'callback': callback,
	}

	return render(req, 'it/message.html', data)

def error(req, title='提交失败!', errors=('无POST数据',)):
	'''通用错误处理视图,提供主视图调用'''
	if not isinstance(errors, tuple):
		errors = (errors,)
	data = {
		'title': title,
		'errors': errors,
	}

	return render(req, 'it/error.html', data)

